// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// k [author] rhyme_lph
// H [email]  rhymelph@gmail.com
// K [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/transaction_entity.dart';
import 'package:finance_app/src/provider/all_reports/fixed_asset/linked_expense_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';
import 'package:finance_app/src/utils/transaction_type_utils.dart';
import 'package:finance_app/src/widgets/button/add_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/select/transaction_record_radio_item.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "linkedExpensePage")
class LinkedExpensePage extends StatefulWidget {
  final TransactionEntity select;

  const LinkedExpensePage({Key key, this.select}) : super(key: key);

  @override
  _LinkedExpensePageState createState() => _LinkedExpensePageState();
}

class _LinkedExpensePageState extends State<LinkedExpensePage>
    with PagePresenter<LinkedExpensePage, LinkedExpenseProvider> {
  @override
  void initState() {
    super.initState();
    // provider.filterIssueTo = widget.filterIssueTo;
    provider.select = widget.select;
  }

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: S.current.linked_expense,
      );

  @override
  Widget get buildEmptyWidget => ColoredBox(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            AppSpaces.h20,
            SearchInputField(
              controller: provider.searchController,
              focusNode: provider.searchFocusNode,
            ),
            AppSpaces.grayH05,
            Expanded(
              child: super.buildEmptyWidget,
            ),
          ],
        ),
      );

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            AppSpaces.h20,
            SearchInputField(
              controller: provider.searchController,
              focusNode: provider.searchFocusNode,
            ),
            NormalFormWrapper(
              child: AddButton(
                title: S.current.add_expense,
                onTap: provider.onNavAddExpense,
              ),
            ),
            AppSpaces.grayH05,
            Expanded(
              child: listBuilder<String>(
                selector: (_, __) => __.searchController.text,
                builder: (BuildContext context, String value, Widget child) =>
                    SmartRefresher(
                  controller: provider.refreshController,
                  onRefresh: provider.onRefresh,
                  onLoading: provider.onLoadMore,
                  enablePullUp: provider.hasUp,
                  child: ListView(
                    children: buildSearchWidget(value),
                  ),
                ),
              ),
            ),
          ],
        ),
      );

  List<Widget> buildSearchWidget(String value) {
    List<Widget> slivers;
    if (provider.searchController.text.isNotEmpty) {
      slivers = provider.data
          .toList()
          .where(_onSearchInputGroup)
          .map((e) => buildSliverItem(e))
          .toList();
    } else {
      slivers = provider.data.toList().map(buildSliverItem).toList();
    }
    return slivers;
  }

  Widget buildSliverItem(TransactionEntity data) {
    return listBuilder<Tuple2<TransactionEntity, bool>>(
      selector: (_, __) => Tuple2(
          data,
          __.select?.id == data.id ||
              __.select?.transactionableId == data.transactionableId),
      builder: (BuildContext context, Tuple2<TransactionEntity, bool> value,
              Widget child) =>
          TransactionRecordRadioItem(
        onTap: () => provider.onSelect(value.item1),
        tag: TransactionTypeUtils.getTransactionType(
            value.item1.transactionType),
        name: value.item1.name ?? '',
        currencyCode: value.item1.currencyCode,
        time: DateTimeUtils.formatDateTimeString(value.item1.issuedAt),
        amount: value.item1.total?.toDouble(),
        billNumber: value.item1.number,
        isUnpaid:
            value.item1.status == 'open' && value.item1.employeeId == null,
        status: value.item1.isOverdue == 1 && value.item1.status == 'open'
            ? "Overdue"
            : FormUtils.getStatus(
                TransactionTypeUtils.getTransactionTypeStatus(
                    value.item1.transactionType),
                value.item1.status,
                value.item1.status == 'open' && value.item1.employeeId == null
                    ? 1
                    : 0),
        isSelect: value.item2,
      ),
    );
  }

  bool _onSearchInputGroup(TransactionEntity element) {
    String searchInput = provider.searchController.text;
    return RegExpUtils.getSearchRegExp(searchInput).hasMatch(element.name);
  }
}
